package com.chidopi.market.aa.dao.impl;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.chidopi.cdf.tag.ITagDao;


public class TagDaoImpl implements ITagDao {
	private static Logger logger = LoggerFactory.getLogger(TagDaoImpl.class);

	private SimpleJdbcTemplate simpleJdbcTemplate;

	@Autowired
	public void init(DataSource datasource) {
		this.simpleJdbcTemplate = new SimpleJdbcTemplate(datasource);
	}

	public String getCSS(Object username, Object itemID) {
		StringBuffer sql = new StringBuffer("select a.VISABLE, a.ENABLE, b.FUNCTION_ID, a.ITEM_ID ");
		sql.append("from Role2FunctionItem a, Role2Function b, Account2Role c, FunctionItems d ");
		sql.append("where c.account_id=? and c.role_id=b.role_id and b.role_id=a.role_id and a.item_id=d.id and d.enable_flag='Y' ");
		if (itemID.toString().matches("\\d+")) {
			sql.append("and d.id=? ");
		} else {
			sql.append("and d.alias=? ");
		}
		List<Map<String, Object>> list = this.simpleJdbcTemplate.queryForList(sql.toString(), username, itemID);
		String returnCSS = ITagDao.VISABLE_STYLE;
		if (null == list || list.size()==0) {
			// can call getCSS indicate the user can access the function url
			logger.debug(sql.toString());
			logger.debug("UserID[" + username + "] be permitted for all");
			return returnCSS;
		}

		Map<String, Object> map = list.get(0);
		String visableFlag = (String) map.get("VISABLE");
		sql = new StringBuffer("");
		if ("N".equals(visableFlag)) {
			sql.append("select HIDDEN_STYLE as FLAG ");
			returnCSS = ITagDao.HIDDEN_STYLE;
		} else {
			String enableFlag = (String) map.get("ENABLE");
			if ("N".equals(enableFlag)) {
				sql.append("select DISABLE_STYLE as FLAG ");
				returnCSS = ITagDao.DISABLE_STYLE;
			}
		}
		if (sql.length() > 0) {
			Object item = map.get("ITEM_ID");	// itemID maybe is ID or alias
			sql.append("from ItemStyles where item_id in (-1, ?) and function_id in (-1, ?) and enable_flag='Y' ");
			sql.append("order by item_id desc, function_id desc ");
			// order by item_id+function_id, -1 + function_id, -1 + -1
			List<Map<String, Object>> list1 = this.simpleJdbcTemplate.queryForList(
				sql.toString(), item, map.get("FUNCTION_ID"));
			if (null != list1 && list1.size() > 0) {
				String flag = (String) list1.get(0).get("FLAG");
				if (flag != null) returnCSS = flag;
			}
		}
		logger.debug("UserID[" + username + "] return " + returnCSS);
		return returnCSS;
	}

}
